//
//  BindingViewModel.swift
//  Alamofire
//
//  Created by 易先生 on 2022/9/9.
//

import UIKit
import RxSwift
import RxCocoa
import CoreBluetooth
import CRPSmartRing

class BindingViewModel: NSObject {

	public var scanCount = 0

    public var models: [BindingModel] = []

	public let devicesRelay = BehaviorRelay<[BindingModel]>(value: [])

	public let finishScanRelay = PublishRelay<[BindingModel]>()
    
	private var scanTimer: Timer!
    
    private var bandConfigModels: [BandConfigModel] = BandConfigModel.all()
    
   
	public func scan() {
		scanCount = 0

        //TODO: - 临时 移除绑定设备
        self.remove()
        self.models.removeAll()
        
      
        let localNames = bandConfigModels.map { $0.name }
        let versions = bandConfigModels.map { $0.version }
        
        BluetoothManager.shared.scan(20) { [weak self] newDiscoveries in
            guard let self = self else { return }
            // 将符合名称命名的加入到扫描列表
//            self.discoverys = self.bindDevices
            newDiscoveries.forEach { discovery in
                
                guard let localName = discovery.localName, let mac = discovery.mac else {
                    return
                }
                
                if localName.isEmpty || mac.isEmpty {
                    return
                }
              
                print("localName: \(localName)")
                print("mac: \(discovery.mac ?? "")")
                print("color: \(discovery.info?.color ?? -1)")
            
                let hide = discovery.hide ?? 1
                print("hide: \(hide)")
                
                guard let localName = discovery.localName, !localName.isEmpty else {
                    return
                }
                if localNames.contains(localName) && versions.contains(discovery.ver) {
                    
                    // 不需要重复加入
                    if self.models.contains(where: { $0.discovery.mac == discovery.mac }) {
                        return
                    }
                    
                    guard let index = localNames.firstIndex(of: localName), let info = discovery.info else {
                        return
                    }
                    let bandConfigModel = self.bandConfigModels[index]
                    
                    guard let colorIndex = bandConfigModel.colors.firstIndex(of: "\(info.color)") else { return }
                    let imageURL = bandConfigModel.logo[colorIndex]
                    
                    let model = BindingModel(discovery: discovery, imageURL: imageURL)
                    
                    if discovery.hide == 1 { // 在充电,排前面
                        self.models.insert(model, at: 0)
                    } else {
                        self.models.append(model)
                    }
 
                    if self.models.count > 200 {
                        BluetoothManager.shared.interruptScan()
                    }
                }
            }
           
        } completionHandler: { [weak self] result, error in
            guard let self = self else { return }
            if self.models.count > 0 {
            
                self.finishScanRelay.accept(self.models)
            }
        }
        
        scanTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true, block: {[weak self] _ in
            
            self?.reloadTableData()
            
        })
        
        RunLoop.current.add(scanTimer, forMode: .common)
    }

	@objc func reloadTableData() {

		scanCount += 1
		if scanCount > 5 {
			scanTimer.invalidate()
			scanCount = 0
		}
		self.devicesRelay.accept(self.models)
	}
    
    
    /// 中断扫描
    public func interruptScan() {
        BluetoothManager.shared.interruptScan()
        
    }
    
    public func remove() {
        BluetoothManager.shared.remove {[weak self] state in
        
            
            
        }
    }
    
    /// 清除旧数据
    public func clean() {
        interruptScan()
        scanCount = 0
        self.models = []
        finishScanRelay.accept(self.models)
    }
    
    public func connect(_ model: BindingModel) {
        
        BluetoothManager.shared.connect(model.discovery)
        
    }
    
    public func saveDeviceInfo(_ model: BindingModel) {
        
        // 保存戒指信息
       let deviceInfo = DeviceInfo.current()
        if let info = model.discovery.info, let adress = model.discovery.mac {
            let color = DeviceInfo.RingColorType(rawValue: info.color) ?? .unkown
            let info = DeviceInfo.RingInfo(adress: adress, color: color, size: info.size, type: info.type, imageURL: model.imageURL)
            info.save()
        }
        
        if let hide = model.discovery.hide {
            deviceInfo.hide = hide
        }
        
        deviceInfo.save()
        
    }
}
